package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    public void saveFlavor(DishDto dishDto) {
        this.save(dishDto);
        Long id = dishDto.getId();
        ArrayList<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> collect = flavors.stream().map(fla -> {
            fla.setDishId(id);
            return fla;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(collect);
    }

    @Override
    public DishDto updatewhithFlavor(Long id) {
        DishDto dishDto = new DishDto();
        Dish byId = this.getById(id);

        BeanUtils.copyProperties(byId,dishDto);
        LambdaQueryWrapper<DishFlavor>lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,byId.getId());

        ArrayList<DishFlavor> list = (ArrayList)dishFlavorService.list(lqw);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public void updatewhith(DishDto dishDto) {
        this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);
        ArrayList<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> collect = flavors.stream().map(iter -> {
            iter.setDishId(dishDto.getId());
            return iter;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(collect);
    }
}
